import Taro from "@tarojs/taro";

const tmplIdMap = {
  settled: {
    title: "商家入驻",
    // tmplIds: ["b3UmUsRYEdexYC9aIy6TJ-Kg7wgxXSQpUsn0gf5BN60"],
    // 新模板
    tmplIds: ["b3UmUsRYEdexYC9aIy6TJ-f-ZPgfVxF4K2OIDkMtabc"],
  },
  enroll: {
    title: "活动报名",
    tmplIds: ["wWdF6Wnmt_8oRNJHZr-C0e137cVuvz7uo-v4M5zcxeQ"],
  },
  staff: {
    title: "店员申请",
    tmplIds: ["b3UmUsRYEdexYC9aIy6TJ-Kg7wgxXSQpUsn0gf5BN60"],
  },
};

const useSubscribeMessage = (type: keyof typeof tmplIdMap) => {
  // const subscribeSwitch = ref(false);

  const { title, tmplIds } = tmplIdMap[type];

  const showModal = async () => {
    const { confirm } = await Taro.showModal({
      title: "开启订阅通知",
      content: `开启“订阅通知”和“${title}”`,
    });

    if (confirm) {
      const { subscriptionsSetting } = await Taro.openSetting({
        withSubscriptions: true,
      });

      const rejected = findRejected(subscriptionsSetting.itemSettings);

      return rejected;
    }
  };

  const findRejected = (source: any) =>
    tmplIds.find((e) => !source?.[e] || source?.[e] == "reject");

  const subscribe = async () => {
    return Taro.requestSubscribeMessage({
      entityIds: [],
      tmplIds,
    })
      .then((res) => {
        const rejected = findRejected(res);
        if (rejected) return Promise.reject({ [rejected]: "reject" });
      })
      .catch((err) => {
        console.error("-----err", err);
        return showModal();
      });
  };

  // const checkSubscribe = async () => {
  //   const res = await Taro.getSetting({
  //     withSubscriptions: true,
  //   });

  //   const { subscriptionsSetting } = res;

  //   subscribeSwitch.value =
  //     subscriptionsSetting.mainSwitch &&
  //     !findRejected(subscriptionsSetting.itemSettings);
  // };

  // checkSubscribe();

  return subscribe;
};

export default useSubscribeMessage;
